package com.tbryant.test.redis.usagescenarios;

import com.tbryant.test.redis.RedisConstant;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;

import java.io.IOException;

/**
 * 使用有序集合实现限流
 * @auther TBryant
 * @date 2021/5/27 13:44
 */
public class CurrentLimiter {
    private static final Jedis JEDIS = new Jedis(RedisConstant.REDIS_IP, RedisConstant.REDIS_PORT);

    /**
     * @param value 不允许重复，否则会产生误差
     */
    static boolean doCurrentLimiterValid(String apiName, String value, int maxCount) {
        long currentTimeMillis = System.currentTimeMillis();
        long score = currentTimeMillis / 1000;
        Pipeline pipe = JEDIS.pipelined();
        pipe.multi();
        // 删除一秒之前的数据
        pipe.zremrangeByScore(apiName, 0, score - 1);
        pipe.zadd(apiName, score, value);
        Response<Long> count = pipe.zcard(apiName);
        // 设置过期时间
        pipe.expire(apiName, 3);
        pipe.exec();
        try {
            pipe.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return count.get() <= maxCount;
    }
}
